<script>
import { eventHub } from '../utils/event'

export default {
  name: 'Dropdown',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visibility: false
    }
  },
  watch: {
    visibility (value) {
      value ? this._enter() : this._leave()
    }
  },
  computed: {
    currentMenuNode() {
      return this._getMenuNode()
    }
  },
  mounted() {
    this.visible ? this._enter() : this._leave()
  },
  methods: {
    _toggleMenuVisible(visibility) {
      if (this.visibility !== visibility) {
        this.visibility = visibility
      }
    },

    _getMenuNode() {
      let childNodes = Array.prototype.slice.call(this.$el.childNodes)
      for (let childNode of childNodes) {
        if (childNode.nodeType === 1 && childNode.className.indexOf('dropdown-menu') !== -1) {
          return childNode
        }
      }
    },

    _enter() {
      this.currentMenuNode.style.display = ''
    },

    _leave() {
      this.currentMenuNode.style.display = 'none'
    },

    onMouseEnter() {
      this._toggleMenuVisible(true)
    },

    onMouseLeave() {
      this._toggleMenuVisible(false)
    }
  },
  created() {
    eventHub.$on('show-dropdown', (msg) => {
      this._toggleMenuVisible(true)
    })
  },
  beforeDestroy() {
    eventHub.$off('show-dropdown')
  }
}
</script>

<template>
  <div class="dropdown">
    <span class="dropdown-toggle"
      @mouseenter="onMouseEnter"
      @mouseleave="onMouseLeave">
      <slot name="toggle"></slot>
    </span>
    <div class="dropdown-menu"
      @mouseenter="onMouseEnter"
      @mouseleave="onMouseLeave">
      <slot name="menu"></slot>
    </div>
  </div>
</template>

<style>
.dropdown {
  position: relative;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 9999;
  margin: 2px 0 0;
  padding: 0;
}
</style>
